import gc
import traceback

from global_ver import es_req, capture_logger


def scroll_slice_method_test(scroll_exp, session_alive):
    final_result = []
    try:
        capture_logger.info(f"[提数队列]清理滚动ID")
        es_req.clear_all_scroll()
        res = es_req.start_scroll(exp=scroll_exp, scroll=str(session_alive), index="arkime_sessions3-*")
        res = res.json()
        if '_scroll_id' not in res:
            capture_logger.info(f"[提数队列]获取失败：{res}")
            return []
        scroll_id = res['_scroll_id']
        results = res['hits']['hits']
        final_result.extend(results)
        if len(results) == 0:
            capture_logger.info("[提数队列]没有数据")
            return []
    except Exception as e:
        capture_logger.info("[提数队列]首次请求报错:")
        traceback.print_exc()
        return []
    while True:
        try:
            res = es_req.scroll_by_id(scroll_id=scroll_id, scroll=str(session_alive)).json()
            if '_scroll_id' not in res:
                capture_logger.info(f"[提数队列]获取session失败:{res}")
                break
            current_scroll_id = res['_scroll_id']
            current_data = res['hits']['hits']
            if len(current_data) == 0:
                break
            else:
                scroll_id = current_scroll_id
                final_result.extend(current_data)
                gc.collect()
        except Exception as e:
            capture_logger.info(f"[提数队列]查询出错：{e},将继续查询")
            traceback.print_exc()
            continue
    capture_logger.info(f"[提数队列]最终获取:{len(final_result)}")
    return final_result
